package Shiwu;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class ShiWu1 {
    @Test//只要涉及到事务就一定要开启
    public void test() throws SQLException {
        Connection connection=null;
        Statement statement=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");         //1加载驱动
            connection= DriverManager.getConnection("jdbc:mysql:////test2","root","root");
 //2创建语句执行者
            statement = connection.createStatement();
            //3编写sql语句
            //开启事务将自动提交改成手动提交
            connection.setAutoCommit(false);
            //减钱
            statement.executeUpdate("update account set account=account-500 where id=1");
            int i=10/0;
            //加钱
            statement.executeUpdate("update account set account=account+500 where id=2");
                  //手动提交
            connection.commit();

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            connection.rollback();
        }finally {
            //释放资源
            connection.close();
            statement.close();
        }

    }

}
